/**
 * 
 */
package com.the9tcat.funnyalarmclock.oauth;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.List;

import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;

/**
 * @author jianhpin
 * 
 */
public class OauthHttp {
	public static String stringByGet(String url) {
		HttpClient client = new DefaultHttpClient();
		HttpGet get = new HttpGet(url);
		HttpResponse response = null;
		InputStream is = null;
		try {
			response = client.execute(get);
			is = response.getEntity().getContent();
		} catch (ClientProtocolException e) {
			System.err.println(e.toString());
		} catch (IOException e) {
			System.err.println(e.toString());
		}
		return stringFromStream(is);
	}

	public static String stringByPOST(String request_url,
			List<BasicNameValuePair> postData) {
		HttpClient client = new DefaultHttpClient();
		HttpPost post = new HttpPost(request_url);
		
		String result = "";
		try {
			if (postData != null) {
			    UrlEncodedFormEntity entity = new UrlEncodedFormEntity(postData);
	            post.setEntity(entity);
			}
			HttpResponse response = client.execute(post);
			InputStream is = response.getEntity().getContent();
			result = OauthHttp.stringFromStream(is);
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (ClientProtocolException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
		return result;
	}

	/**
	 * 将InputStream转化成String.
	 * 
	 * @param is
	 *            the is
	 * @return the string
	 */
	public static String stringFromStream(InputStream is) {
		BufferedReader br = new BufferedReader(new InputStreamReader(is));
		StringBuffer sb = new StringBuffer();
		String line = "";
		try {
			while ((line = br.readLine()) != null) {
				sb.append(line);
				sb.append("\n");
			}
		} catch (IOException e) {
			System.err.println(e.toString());
		} finally {
			try {
				is.close();
				br.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return sb.toString();
	}
}
